<template>
  <div class="pending-view">
    <van-nav-bar
        title="挂单"
        left-arrow
        @click-left="onClickLeft"
        fixed
    />

    <div class="pending-form">
      <div class="form-item">
        <div class="form-label">
          <span class="required">*</span>
          <span class="label-text">挂单原因</span>
        </div>
        <van-field
            v-model="formData.limitone"
            type="textarea"
            rows="4"
            placeholder="请填写挂单原因"
            required
        />
      </div>

      <!-- 确定按钮 -->
      <div class="submit-btn">
        <van-button type="primary" block @click="handlePending">确定</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { NavBar, Field, Button, Toast } from 'vant';

export default {
  name: 'PendingView',
  components: {
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [Button.name]: Button,
  },
  data() {
    return {
      formData: {
        limitone: '',      // 挂单原因
        limitstatus: 0,    // 挂单状态：0-挂单中
        limitshipping: '', // 关联的工单ID
      },
      updateData: {
        id: null,
        shippingstatus: 4  // 4表示已派单（挂单状态）
      }
    }
  },
  methods: {
    onClickLeft() {
      this.$router.back()
    },
    handlePending() {
      if (!this.formData.limitone.trim()) {
        Toast('请输入挂单原因');
        return;
      }

      // 先添加挂单记录
      this.axios.post('http://localhost:9999/api-central-service/shipping/limit', this.formData)
          .then(res => {
            if (res.data.code === 1) {
              // 添加成功后更新工单状态
              this.axios.post('http://localhost:9999/api-central-service/shipping/update', this.updateData)
                  .then(res => {
                    if (res.data.code === 1) {
                      Toast.success('挂单成功');
                      setTimeout(() => {
                        this.$router.push('/ticket');
                      }, 1500);
                    } else {
                      Toast.fail(res.data.message || '状态更新失败');
                    }
                  })
                  .catch(() => {
                    Toast.fail('状态更新失败，请重试');
                  });
            } else {
              Toast.fail(res.data.message || '挂单失败');
            }
          });
    }
  },
  mounted() {
    const id = this.$route.query.id;
    if (!id) {
      Toast('工单ID不能为空');
      this.$router.back();
      return;
    }
    this.updateData.id = id;
    this.formData.limitshipping = id;
  }
}
</script>

<style scoped>
.pending-view {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}

.pending-form {
  padding: 16px;
}

.form-item {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 8px;
}

.form-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #323233;
}

.required {
  color: #ee0a24;
  margin-right: 4px;
}

.submit-btn {
  margin-top: 24px;
  padding: 0 16px;
}

:deep(.van-field__control) {
  min-height: 100px;
}
</style>